package com.fly.hello.web;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.spi.StandardLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fly.core.JsonResult;
import com.fly.core.utils.IPUtils;
import com.fly.core.utils.SpringContextUtils;
import com.fly.hello.runner.StaticCode;
import com.fly.hello.runner.StaticCode2;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(tags = "演示接口")
@Slf4j
@RestController
@RequestMapping("/show")
@ConditionalOnWebApplication
public class ShowController
{
    @Autowired
    HttpServletRequest request;
    
    @Autowired
    StaticCode staticCode;
    
    @ApiOperation("系统信息")
    @GetMapping(value = "/info")
    public Map<String, String> info()
        throws UnknownHostException
    {
        Map<String, String> infoMap = new HashMap<String, String>(2);
        infoMap.put("client_ip", IPUtils.getIpAddr(request));
        infoMap.put("server_ip", InetAddress.getLocalHost().getHostAddress());
        log.info("================== profile: {}", SpringContextUtils.getActiveProfile());
        staticCode.print();
        StaticCode2.print();
        return infoMap;
    }
    
    @ApiOperation("更新日志level")
    @PostMapping("/updateLogLevel")
    public JsonResult<String> updateLogLevel()
    {
        LoggerContext loggerContext = LoggerContext.getContext(false);
        LoggerConfig loggerConfig = loggerContext.getConfiguration().getRootLogger();
        Level now = loggerConfig.getLevel();
        
        // 100 -> 600
        int next = now.getStandardLevel().intLevel() % 600 + 100;
        Level level = Level.toLevel(StandardLevel.getStandardLevel(next).name());
        loggerConfig.setLevel(level);
        loggerContext.updateLoggers();
        
        System.err.println("OFF(0), FATAL(100), ERROR(200), WARN(300), INFO(400), DEBUG(500), TRACE(600) => " + Level.toLevel(StandardLevel.getStandardLevel(next).name()));
        return JsonResult.success("系統当前日志级别：" + level.name());
    }
    
    @ApiOperation("文件读取")
    @GetMapping("/read-file")
    public String readFile()
        throws IOException
    {
        Resource resource = new ClassPathResource("data/bak/data.json");
        String protocol = resource.getURL().getProtocol();
        log.info("###### protocol: {}", protocol);
        // 协议： jar、file
        if ("jar".equals(protocol))
        {
            log.info("IOUtils.toString");
            try (InputStream inputStream = resource.getInputStream())
            {
                return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
            }
        }
        log.info("FileUtils.readFileToString");
        return FileUtils.readFileToString(resource.getFile(), StandardCharsets.UTF_8);
    }
    
    @ApiOperation("文件下载")
    @GetMapping(value = "/download-file", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void downloadFile(HttpServletResponse response)
        throws IOException
    {
        response.setHeader("Content-Disposition", "attachment;filename=json.log");
        Resource resource = new ClassPathResource("data/bak/data.json");
        try (InputStream inputStream = resource.getInputStream())
        {
            IOUtils.copy(inputStream, response.getOutputStream());
        }
    }
    
    @ApiOperation("auto")
    @PostMapping(value = "/auto", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] auto(MultipartFile file, MultipartFile line)
        throws IOException
    {
        BufferedImage image = ImageIO.read(file.getInputStream());
        BufferedImage insert = ImageIO.read(line.getInputStream());
        Graphics2D graph = image.createGraphics();
        graph.drawImage(insert, 50, 1525, 960, 100, null);
        
        // 销毁图形界面资源
        graph.dispose();
        
        // 输出
        try (ByteArrayOutputStream os = new ByteArrayOutputStream())
        {
            ImageIO.write(image, "jpg", os);
            return os.toByteArray();
        }
    }
}
